package org.kaer.election.fragment;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.kaer.election.R;
import org.kaer.election.bean.SelectedElection;
import org.kaer.election.utils.BitmapStream;
import org.kaer.election.utils.BitmapUtils;
import org.kaer.election.utils.JSONKeys;
import org.kaer.election.utils.LogUtils;
import org.kaer.election.utils.SharedConfig;
import org.kaer.election.utils.UdpHelper;

import java.util.Date;

/**
 * Created by lizj on 2016/7/6.
 */
public class SearchServerFragment extends BaseFragment implements View.OnClickListener, UdpHelper.UdpSearchResultInterface {
    private ImageView searchIv;
    private LinearLayout commonbgLL;
    UdpHelper udphelper = null;
    private boolean allowSearched;
    private Handler mHanlder = new Handler();
    private String serverIp;
    private TextView versionTv;

    public static SearchServerFragment newInstance() {
        return new SearchServerFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_searchserver;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        searchIv = (ImageView) findView(R.id.searchServerIv);
        versionTv = (TextView) findView(R.id.versionTv);
        try {
            udphelper = new UdpHelper(mContext, this);
        } catch (Exception e) {
            // TODO: handle exception
            Toast.makeText(mContext, "初始化搜索失败!", Toast.LENGTH_SHORT).show();
        }
        setMargins(searchIv, 0, 200, 0, 0);
        searchIv.setImageBitmap(BitmapUtils.scaleBitmap(mContext,
                BitmapFactory.decodeResource(getResources(), R.drawable.search_server), 1.618 / (1 + 1.618)));

        try {
            PackageInfo info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            versionTv.setText("版本 : " + info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        getHoldingActivity().initTitle(R.string.app_name);

    }


    private void searchServer() {
        if (allowSearched) {
            showProgressDialog("正在搜索周围的服务器...");
            searchIv.setEnabled(false);
            udphelper.sendMsg();
        }
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        searchIv.setEnabled(true);
        allowSearched = true;
        serverIp = null;
        mHanlder.postDelayed(r, 2000);
    }

    @Override
    public void onPause() {
        super.onPause();
        allowSearched = false;
        mHanlder.removeCallbacks(r);

    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        searchIv.setEnabled(true);
        dismissDialog();
        super.onStop();
    }

    @Override
    public void searchResult(int result, Intent intent) {
        // TODO Auto-generated method stub
        dismissDialog();

        searchIv.setEnabled(true);
        String msg = intent.getStringExtra("msg");
        serverIp = intent.getStringExtra("ip");
        LogUtils.i("serverIp = " + serverIp);
        LogUtils.i("msg = " + msg);

        if (serverIp == null || serverIp.length() <= 6) {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            mHanlder.postDelayed(r, 3000);
        } else {
            new ConnectServerTask().execute(serverIp);
        }

    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            LogUtils.i("mExampleClient.getConnectState() = " + mExampleClient.getConnectState() + ",serverIp = " + serverIp);
            if (TextUtils.isEmpty(serverIp)) {
                searchServer();
            } else if (mExampleClient.getConnectState() != mExampleClient.STATE_CONNECTED) {
                new ConnectServerTask().execute(serverIp);
            } else {
                new GetElectionTask().execute();

            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchServerIv:
                searchServer();
                break;
            default:
                break;
        }
    }

    class ConnectServerTask extends AsyncTask<String, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            if (mExampleClient.getConnectState() == mExampleClient.STATE_CONNECTED)
                mExampleClient.disconnectServer();
            showProgressDialog("正在连接服务器...");
        }

        @Override
        protected Integer doInBackground(String... params) {
            // TODO Auto-generated method stub
            int state = mExampleClient.connectServer(params[0], 6310, mContext); //// 连接websocket

            return state;
        }

        @Override
        protected void onPostExecute(Integer result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dismissDialog();
            if (result == mExampleClient.STATE_CONNECTED) {
                // Toast.makeText(activity, "服务器已连接",
                // Toast.LENGTH_SHORT).show();
                new GetElectionTask().execute();
            } else {
                mHanlder.postDelayed(r, 2000);
            }
        }
    }

    class GetElectionTask extends AsyncTask<String, Integer, SelectedElection> {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            showProgressDialog("正在获取投票信息...");
        }

        @Override
        protected SelectedElection doInBackground(String... params) {
            // TODO Auto-generated method stub

            return mExampleClient.selectedElection();
        }

        @Override
        protected void onPostExecute(SelectedElection result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            dismissDialog();

            if (result != null) {
                parseElection(result);

            } else {
                Toast.makeText(mContext, "未获取到投票信息", Toast.LENGTH_SHORT).show();
                mHanlder.removeCallbacks(r);
                mHanlder.postDelayed(r, 2000);
            }

        }
    }

    public void parseElection(SelectedElection election) {
        // TODO Auto-generated method stub
        if (election.electionId == 0) {
            Toast.makeText(mContext, "未获取到投票数据", Toast.LENGTH_SHORT).show();
            mHanlder.removeCallbacks(r);
            mHanlder.postDelayed(r, 2000);
            return;

        }
        LogUtils.i("election " + election.toString());
        LogUtils.i("election.startTime " + election.startTime);
        LogUtils.i("election.endTime " + election.endTime);

        int ret = BitmapStream.canstart(new Date(), election.startTime, election.endTime);
        if (ret == -1) {
            Toast.makeText(mContext, "开始或结束时间无效", Toast.LENGTH_SHORT).show();

        } else if (ret == 1) {
            Toast.makeText(mContext, "选举未开始，请耐心等待", Toast.LENGTH_SHORT).show();

        }

        if (election.positionList != null) {
            if (election.positionList.length == 0) {
                // close();
                mHanlder.removeCallbacks(r);
                mHanlder.postDelayed(r, 2000);

                Toast.makeText(mContext, "职位信息为空 ", Toast.LENGTH_SHORT).show();
            }
        } else {
            // close();
            mHanlder.removeCallbacks(r);
            mHanlder.postDelayed(r, 2000);

            Toast.makeText(mContext, "职位信息为空 ", Toast.LENGTH_SHORT).show();
        }
        // 3、判断选区ID 如果选区ID 为0 提示一下
        if (election.regionId == 0) {
            Toast.makeText(mContext, "选取ID为0 ", Toast.LENGTH_SHORT).show();
            mHanlder.removeCallbacks(r);
            mHanlder.postDelayed(r, 2000);
            return;
        }

        goToReadActivity(election);

    }

    private void goToReadActivity(SelectedElection election) {
        try {
            String data = new Gson().toJson(election);
            mBundle.putString(JSONKeys.Voter.ElectionData, data);
            mBundle.putString(JSONKeys.Voter.ElectionIP, serverIp);
            SharedConfig.getInstance(mContext).writeData("type", election.getElectionType());
            addFragment(ReadIDFragment.newInstance(mBundle));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
